﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace RadarMonitor.Alarm
{
    public class AudioHandler
    {
        private static readonly Lazy<AudioHandler>
           lazy =
           new Lazy<AudioHandler>
               (() => new AudioHandler());

        public static AudioHandler Instance { get { return lazy.Value; } }
        private SoundPlayer AlarmPalyer;

        private bool _IsPlayingAlarm =false;

        public bool IsPlayingAlarm
        {
            get { return _IsPlayingAlarm =false; }
            private set { _IsPlayingAlarm = value;
                OnPropertyChanged("IsPlayingAlarm");
            }
        }

        
        private AudioHandler()
        {
            try
            {
                AlarmPalyer = new SoundPlayer(Properties.Resources.Alarm);
                AlarmPalyer.LoadAsync();
            }
            catch { }

        }

        public void palyAlarm(RadarMonitorSource source, RadarMonitorResultCode code, string msg)
        {
            AlarmCode = (int)code;
            if (IsPlayingAlarm)
                return;
            IsPlayingAlarm = true;
            AlarmPalyer.PlayLooping();
            Task.Delay(10000).ContinueWith(_ =>
            {
                AlarmPalyer.Stop();
                IsPlayingAlarm = false;
            }); 
        }

        public void cleanAlarm()
        {
            AlarmPalyer.Stop();
            IsPlayingAlarm = false;
        }


        private int _AlarmCode;

        public int AlarmCode
        {
            get { return _AlarmCode; }
            set {
                _AlarmCode = value;
                OnPropertyChanged("AlarmCode");
            }
        }

        #region 属性变化通知
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName = "")
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}
